package com.sctvcloud.qingchuan.ui.activities;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.SimpleTarget;
import com.canyinghao.canrefresh.CanRefreshLayout;
import com.canyinghao.canrefresh.other.CanRecyclerViewHeaderFooter;
import com.jiongbull.jlog.JLog;
import com.luck.picture.lib.PictureExternalPreviewActivity;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.entity.LocalMedia;
import com.ruihang.generalibrary.ui.util.OnItemInternalClick;
import com.ruihang.generalibrary.ui.widget.CustomEXImageView;
import com.ruihang.generalibrary.ui.widget.CustomFontTextView;
import com.ruihang.generalibrary.utils.DateUtils;
import com.ruihang.generalibrary.utils.DensityUtil;
import com.ruihang.generalibrary.utils.ListUtils;
import com.ruihang.generalibrary.utils.UrlUtils;
import com.sctvcloud.qingchuan.R;
import com.sctvcloud.qingchuan.application.Constances;
import com.sctvcloud.qingchuan.base.BaseDetailActivity;
import com.sctvcloud.qingchuan.beans.ADynamicsItem;
import com.sctvcloud.qingchuan.beans.DeclareBean;
import com.sctvcloud.qingchuan.beans.DoUpEvent;
import com.sctvcloud.qingchuan.beans.FComment;
import com.sctvcloud.qingchuan.beans.FRebellion;
import com.sctvcloud.qingchuan.beans.ImageUr;
import com.sctvcloud.qingchuan.beans.Reply;
import com.sctvcloud.qingchuan.beans.ReplyDetail;
import com.sctvcloud.qingchuan.beans.SingleResult;
import com.sctvcloud.qingchuan.http.AbsNetCallBack;
import com.sctvcloud.qingchuan.http.NetUtils;
import com.sctvcloud.qingchuan.http.ParamsEditor;
import com.sctvcloud.qingchuan.ui.adapter.CommentDetailAdapter;
import com.sctvcloud.qingchuan.ui.adapter.PicAdapter;
import com.sctvcloud.qingchuan.ui.adapter.holder.AnchorHomeDynamicsHolder;
import com.sctvcloud.qingchuan.ui.util.RBaseItemDecoration;
import com.sctvcloud.qingchuan.ui.utils.GlideCircleTransform;
import com.sctvcloud.qingchuan.ui.utils.GlideUtil;
import com.sctvcloud.qingchuan.ui.utils.ItemImagTarget;
import com.sctvcloud.qingchuan.ui.utils.SkipUtil;
import com.sctvcloud.qingchuan.ui.utils.TitleUtils;
import com.sctvcloud.qingchuan.ui.utils.UIUtils;
import com.sctvcloud.qingchuan.utils.UserManager;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 我的申报 详情
 */
public class MyDeclareDetailActivity extends BaseDetailActivity {
    //
//    @BindView(R.id.comment_refresh)
//    protected CanRefreshLayout refreshLayout;
//    @BindView(R.id.can_content_view)
//    protected RecyclerView comment_list;
//    @BindView(R.id.comment_footer)
//    protected CanRecyclerViewHeaderFooter footer;
//    @BindView(R.id.comment_foot_pb)
//    protected ProgressBar pb;
//    @BindView(R.id.comment_foot_loadmore)
//    protected View allLoaded;
//    @BindView(R.id.comment_foot_lay_normal)
//    protected ViewGroup layFootNormal;
//    @BindView(R.id.comment_foot_lay_empty)
//    protected View layFootEmpty;
    @BindView(R.id.item_anchor_home_dynamics_img)
    protected ImageView img;
    @BindView(R.id.item_anchor_dynamics_home_name)
    protected CustomFontTextView name;
    @BindView(R.id.item_anchor_dynamics_home_time)
    protected CustomFontTextView time;
    //    @BindView(R.id.item_anchor_dynamics_home_lable)
//    protected CustomFontTextView lable;
    @BindView(R.id.item_anchor_dynamics_home_page_intro)
    protected TextView intro;
    @BindView(R.id.item_anchor_dynamic_home_pic)
    protected RecyclerView pic_list;

    @BindView(R.id.item_anchor_home_dynamics_video_rl)
    protected ViewGroup video_rl;
    @BindView(R.id.item_anchor_home_dynamics_video_coverImg)
    protected ImageView coverImage;
    @BindView(R.id.item_achor_single_temp)
    protected View singleTemp;
    @BindView(R.id.item_anchor_home_dynamics_video_play)
    protected ImageView play;
    @BindView(R.id.item_anchor_dynamics_home_page_ll_four)
    protected ViewGroup four_ll;
    @BindView(R.id.item_anchor_dynamics_home_page_img1)
    protected CustomEXImageView img1;
    @BindView(R.id.item_anchor_dynamics_home_page_img2)
    protected CustomEXImageView img2;
    @BindView(R.id.item_anchor_dynamics_home_page_img3)
    protected CustomEXImageView img3;
    @BindView(R.id.item_anchor_dynamics_home_page_img4)
    protected CustomEXImageView img4;
    @BindView(R.id.item_anchor_dynamics_home_page_img5)
    protected CustomEXImageView img5;
    @BindView(R.id.item_anchor_dynamics_home_page_img6)
    protected CustomEXImageView img6;
    @BindView(R.id.item_anchor_dynamics_home_page_rl)
    protected ViewGroup rl_type;

    //    @BindView(R.id.tv_anchor_up)
//    protected CustomFontTextView tvUp;
//    @BindView(R.id.tv_anchor_comment)
//    protected CustomFontTextView tvComment;
//    @BindView(R.id.item_anchor_dynamics_home_page_comment)
//    protected LinearLayout llComment;
    private PicAdapter picAdapter;

    @BindView(R.id.rebllion_commit_address_title)
    protected CustomFontTextView address_cv;

    @BindView(R.id.title_top_logo_layout)
    protected LinearLayout title_top_logo_layout;
    @BindView(R.id.title_top_title)
    protected CustomFontTextView title_top_title;
    @BindView(R.id.title_top_share)
    protected CustomFontTextView title_top_share;
//    @BindView(R.id.item_title)
//    protected CustomFontTextView item_title;

    @BindView(R.id.tv_status)
    protected CustomFontTextView tv_status;

    private ItemImagTarget imgTarget;

    private LinearLayoutManager manager;
    private DeclareBean dynamicsItem;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        new TitleUtils(this);
        this.setTypeName(2);//日志统计 主播圈类型

        initView();
    }


    @Override
    protected void initInject() {
        setContentView(R.layout.activity_my_declare_detail);
        butterUnbinder = ButterKnife.bind(this);
    }


    private void initView() {
        title_top_logo_layout.setVisibility(View.GONE);
        title_top_title.setVisibility(View.VISIBLE);
        title_top_title.setText(getText(R.string.tv_my_declare));
//        imgTarget = new ItemImagTarget(coverImage);
//        singleTemp.getViewTreeObserver().addOnGlobalLayoutListener(singleGlobal);


        //   title_top_share.setVisibility(View.VISIBLE);

//        handler = new Handler();
//        manager = new LinearLayoutManager(this, LinearLayoutManager.VERTICAL, false);
//        comment_list.setItemAnimator(new DefaultItemAnimator());
//        comment_list.setLayoutManager(manager);
//        comment_list.addItemDecoration(new RBaseItemDecoration(DensityUtil.dip2px(this, 1),
//                ContextCompat.getColor(this, R.color.colorItemListDivider)));
        Intent intent = getIntent();
        if (intent == null) {
            toast(R.string.data_wrong);
            finish();
            return;
        }
        dynamicsItem = (DeclareBean) intent.getSerializableExtra(EX_DATA);
        initTop(dynamicsItem);
//        requestType = getIntent().getIntExtra(EX_TYPE_NEWS, 4);
        commentType = getIntent().getIntExtra(EX_COMMENT_TYPE, 4);
//        position = getIntent().getIntExtra(DO_UP_POS, -1);


    }


    public void initTop(DeclareBean aDynamicsItem) {
        name.setText(!TextUtils.isEmpty(aDynamicsItem.getUserName()) ? aDynamicsItem.getUserName() : "");

        if (aDynamicsItem.getStatus() == 1) {
            tv_status.setText(getResources().getText(R.string.tv_done));
            tv_status.setTextColor(getResources().getColor(R.color.color_09CEB4));
            tv_status.setVisibility(View.VISIBLE);
        } else if (aDynamicsItem.getStatus() == 0) {
            tv_status.setText(getResources().getText(R.string.tv_doing));
            tv_status.setTextColor(getResources().getColor(R.color.color_0087D8));
            tv_status.setVisibility(View.VISIBLE);
        } else {
            tv_status.setVisibility(View.GONE);
        }

        time.setText(!TextUtils.isEmpty(aDynamicsItem.getCreateTime()) ? DateUtils.timeAgo(DateUtils.getDataDate(aDynamicsItem)) : "");
        intro.setText((TextUtils.isEmpty(aDynamicsItem.getContent()) ? "" : aDynamicsItem.getContent()));
        address_cv.setText(aDynamicsItem.getLocation());

        if (TextUtils.isEmpty(aDynamicsItem.getLocation())) {
            address_cv.setVisibility(View.GONE);
        } else {
            address_cv.setVisibility(View.VISIBLE);
        }


        play.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String contentVideoUrl = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamicsItem.getVideoUrl());
                SkipUtil.skipToVideoPlay(MyDeclareDetailActivity.this, contentVideoUrl, 0, 0);
            }
        });

        if (!TextUtils.isEmpty(aDynamicsItem.getUserAvatar())) {
            GlideUtil.getGlid(MyDeclareDetailActivity.this, aDynamicsItem.getUserAvatar()).diskCacheStrategy(DiskCacheStrategy.NONE).error(R.mipmap.icon_circle_avatar)
                    .placeholder(R.mipmap.icon_circle_avatar).transform(new GlideCircleTransform(MyDeclareDetailActivity.this))
                    .into(img);
        } else {
            img.setImageResource(R.mipmap.icon_circle_avatar);
        }
        int pa = getResources().getDimensionPixelOffset(R.dimen.item_list_large_margin_top);
        if (TextUtils.isEmpty(aDynamicsItem.getVideoUrl()) && !ListUtils.isListValued(aDynamicsItem.getImageList())) {
            rl_type.setVisibility(View.GONE);
        } else {
            rl_type.setVisibility(View.VISIBLE);
        }
        if (TextUtils.isEmpty(aDynamicsItem.getVideoUrl())) {
            play.setVisibility(View.GONE);
            coverImage.setVisibility(View.GONE);

            if (ListUtils.isListValued(aDynamicsItem.getImageList())) {
                if (aDynamicsItem.getImageList().size() == 1) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.VISIBLE);
                    coverImage.setVisibility(View.VISIBLE);
                    four_ll.setVisibility(View.GONE);
//                    singleImg.setVisibility(View.VISIBLE);
//                    GlideUtil.getGlideWithSmall169Def(context, contentImage.get(0).getImageUrl()).into(singleImg);
//                    GlideUtil.getGlideWith11DefNoFit(MyDeclareDetailActivity.this, aDynamicsItem.getImageList().get(0).getImageUrl())
////                            .fitCenter()
////                            .listener(lis)
//                            .into(imgTarget);
                    initImgView(UrlUtils.linkUrls(Constances.ST_BASE_URL,aDynamicsItem.getImageList().get(0).getImageUrl()));
                } else if (aDynamicsItem.getImageList().size() == 4) {
                    pic_list.setVisibility(View.GONE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.VISIBLE);
                    GlideUtil.loadImgWith11Def(MyDeclareDetailActivity.this, aDynamicsItem.getImageList().get(0).getImageUrl(), img1);
                    GlideUtil.loadImgWith11Def(MyDeclareDetailActivity.this, aDynamicsItem.getImageList().get(1).getImageUrl(), img2);
                    GlideUtil.loadImgWith11Def(MyDeclareDetailActivity.this, aDynamicsItem.getImageList().get(2).getImageUrl(), img4);
                    GlideUtil.loadImgWith11Def(MyDeclareDetailActivity.this, aDynamicsItem.getImageList().get(3).getImageUrl(), img5);
                    img3.setImageDrawable(null);
                    img6.setImageDrawable(null);
                } else {
                    initView(aDynamicsItem.getImageList());
                    pic_list.setVisibility(View.VISIBLE);
                    video_rl.setVisibility(View.GONE);
                    four_ll.setVisibility(View.GONE);
                }
            } else {
                pic_list.setVisibility(View.GONE);
                video_rl.setVisibility(View.GONE);
                four_ll.setVisibility(View.GONE);
//                singleImg.setVisibility(View.GONE);
            }
        } else {
            pic_list.setVisibility(View.GONE);
            four_ll.setVisibility(View.GONE);
//            singleImg.setVisibility(View.GONE);
            video_rl.setVisibility(View.VISIBLE);
            coverImage.setVisibility(View.VISIBLE);
            play.setVisibility(View.VISIBLE);
            String coverImageUrl = aDynamicsItem.getCoverImage();
//            DrawableRequestBuilder<String> drb=
//            GlideUtil.getGlideWithMid169DefNoFit(MyDeclareDetailActivity.this, coverImageUrl)
////                            .fitCenter()
////                            .listener(lis)
//                    .into(imgTarget);
            initImgView(UrlUtils.linkUrls(Constances.ST_BASE_URL,coverImageUrl));
        }
    }

    private void initView(List<ImageUr> dataImgs) {
        manager = new GridLayoutManager(MyDeclareDetailActivity.this, 3);
        pic_list.setItemAnimator(new DefaultItemAnimator());
        pic_list.setLayoutManager(manager);
        manager.setSmoothScrollbarEnabled(true);
        manager.setAutoMeasureEnabled(true);
        pic_list.setHasFixedSize(true);
        pic_list.setNestedScrollingEnabled(false);
        if (picAdapter == null) {
            // new UiListMarginUtils().setMargin(context, pic_list, R.dimen.item_list_large_margin_left, R.dimen.item_list_large_margin_right);
            picAdapter = new PicAdapter(MyDeclareDetailActivity.this, dataImgs);
        } else {
            picAdapter.setData(dataImgs);
        }
        pic_list.setAdapter(picAdapter);
    }

    @OnClick(value = {R.id.item_anchor_dynamics_home_page_img1, R.id.item_anchor_dynamics_home_page_img2,
            R.id.item_anchor_dynamics_home_page_img4, R.id.item_anchor_dynamics_home_page_img5})
    public void imgClick(View view) {
        Intent intent = new Intent(MyDeclareDetailActivity.this, PictureExternalPreviewActivity.class);
        switch (view.getId()) {
            case R.id.item_anchor_dynamics_home_page_img1:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
                break;
            case R.id.item_anchor_dynamics_home_page_img2:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 1);
                break;
            case R.id.item_anchor_dynamics_home_page_img4:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 2);
                break;
            case R.id.item_anchor_dynamics_home_page_img5:
                intent.putExtra(PictureConfig.EXTRA_POSITION, 3);

                break;

        }
        List<LocalMedia> images = new ArrayList<LocalMedia>();
        for (ImageUr imageUr : dynamicsItem.getImageList()) {
            LocalMedia localMedia = new LocalMedia();
            localMedia.setPath(Constances.ST_BASE_URL + imageUr.getImageUrl());
            images.add(localMedia);
        }

        intent.putExtra("type", 1);
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, (Serializable) images);
        startActivity(intent);

    }

    @OnClick({R.id.item_anchor_home_dynamics_video_coverImg, R.id.item_anchor_home_dynamics_coverImg})
    public void onlyImgClick(View view) {
        if (dynamicsItem == null || !TextUtils.isEmpty(dynamicsItem.getVideoUrl())
                || dynamicsItem.getImageList() == null || dynamicsItem.getImageList().size() == 0
                || dynamicsItem.getImageList().get(0) == null || TextUtils.isEmpty(dynamicsItem.getImageList().get(0).getImageUrl())) {
            return;
        }
        String path = UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamicsItem.getImageList().get(0).getImageUrl());
        String type = (path.endsWith(".gif") || path.endsWith(".GIF")) ? "image/gif" : "image";
        Intent intent = new Intent(MyDeclareDetailActivity.this, PictureExternalPreviewActivity.class);
        intent.putExtra("type", 1);
        ArrayList<LocalMedia> list = new ArrayList<>();
        list.add(new LocalMedia(path, "", type));
        intent.putExtra(PictureConfig.EXTRA_PREVIEW_SELECT_LIST, list);
        intent.putExtra(PictureConfig.EXTRA_POSITION, 0);
        startActivity(intent);
    }

    @OnClick(value = {R.id.item_anchor_home_dynamics_video_play})
    public void playClick(View view) {
        SkipUtil.skipToVideoPlay(this, UrlUtils.linkUrls(Constances.ST_BASE_URL, dynamicsItem.getVideoUrl())
                , dynamicsItem.getPlayedPos(), 0);

    }

    private ViewTreeObserver.OnGlobalLayoutListener singleGlobal = new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (imgTarget != null && singleTemp.getWidth() > 0) {
                imgTarget.setMxW(singleTemp.getWidth());
                singleTemp.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        }
    };

    private void initImgView(final String path) {
        Glide.with(this)
                .load(path)
                .asBitmap()//强制Glide返回一个Bitmap对象
                .centerCrop()
                .into(new SimpleTarget<Bitmap>() {
                    @Override
                    public void onResourceReady(Bitmap bitmap, GlideAnimation<? super Bitmap> glideAnimation) {
                        int width = bitmap.getWidth();
                        int height = bitmap.getHeight();
                        JLog.e("---------initImgView------width ="+width+"----height ="+height+"------------");
                        JLog.e("---------initImgView------UIUtils.dip2px(MyDeclareDetailActivity.this, 240) ="+UIUtils.dip2px(MyDeclareDetailActivity.this, 240)+"----height ="+height+"------------");
                        FrameLayout.LayoutParams params = (FrameLayout.LayoutParams) coverImage.getLayoutParams();
                        if (height > width) {
                            if (height > UIUtils.dip2px(MyDeclareDetailActivity.this, 240)) {
                                params.width = UIUtils.dip2px(MyDeclareDetailActivity.this, 140);
                                params.height = UIUtils.dip2px(MyDeclareDetailActivity.this, 240);
                            } else {
                                params.height =  height ;
                                params.width =  width ;

                            }
                        } else if (height < width) {
                            if (width > UIUtils.dip2px(MyDeclareDetailActivity.this, 240)) {
                                params.height = UIUtils.dip2px(MyDeclareDetailActivity.this, 140);
                                params.width = UIUtils.dip2px(MyDeclareDetailActivity.this, 240);
                            } else {
                                params.height =  height ;
                                params.width =  width ;
                            }
                        } else {
                            JLog.e("-----initImgView---width = " + width + "---------height = " + height);
                            if (height > UIUtils.dip2px(MyDeclareDetailActivity.this, 140)) {
                                params.height = UIUtils.dip2px(MyDeclareDetailActivity.this, 140);
                                params.width = UIUtils.dip2px(MyDeclareDetailActivity.this, 140);
                            } else {
                                params.height =  height ;
                                params.width =  width ;
                            }
                        }
                        coverImage.setLayoutParams(params);
//                        itemOnlyImg.setImageBitmap(bitmap);
                        Glide.with(MyDeclareDetailActivity.this)
                                .load(path)
                                .error(com.luck.picture.lib.R.drawable.icon_def_1_1)
                                .into(coverImage);
                    }
                });
    }

}
